/*
 * @描述: 
 * @创建者: kilomChou
 * @Date: 2021-05-05 19:20:23
 * @最后编辑: kilomChou
 * @LastEditTime: 2021-05-06 08:51:28
 */
import IConn from "./common/core/net/IConn";
import ProtoDispatcher from "./common/core/net/ProtoDispatcher";
import { ProtoVo } from "./common/data/Proto";
import ws from "ws"
import Game from "./common/game/Game";

export default class Conn implements IConn{

    readonly PD = new ProtoDispatcher();
    id: number;

    constructor(readonly game: Game, readonly socket: ws) {

        socket.binaryType = "arraybuffer";
        game.conn(this);
        socket.onclose = e => {
            game.disConn(this.id);
        }
        socket.onmessage = e => {
            if (e.data instanceof ArrayBuffer) {
                let { protocol, data } = ProtoVo.fromBytes(new Uint8Array(e.data));
                this.onMsg(protocol, data);
            }
        }
    }

    /** 监听协议 */
    on<Proto extends keyof ProtoVo.Def>(proto: Proto, cb: (data: ProtoVo.Def[Proto]) => any): void {
        this.PD.on(proto, cb);
    }

    /** 接收到协议 */
    onMsg<Proto extends keyof ProtoVo.Def>(proto: Proto, data?: ProtoVo.Def[Proto]): void {
        this.PD.onMsg(proto, data);
    }

    /** 发送协议 */
    send<Proto extends keyof ProtoVo.Def>(proto: Proto, data?: ProtoVo.Def[Proto]): void {
        this.socket.send(ProtoVo.toBytes(proto, data));
    }
}